<template>
  <VPage>
    <!-- <DerivedCenter ref="DerivedCenterRef"></DerivedCenter> -->
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm
          :fieldList="fieldList"
          :formOption="optionsDataAll"
          :formData="form"
        >
          <template #create_user="{ value, input }">
            <VCascader
              :model-value="value"
              @update:model-value="input"
              collapse-tags
              class="w-[200px]"
              placeholder="请选择"
            />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <VActionBar :actions="actions">
          <template #left>
            <span class="ml-[16px]"
              >说明：系统定时自动将生效中的燃油费率同步给相关联的各个物流渠道，并更新对应配置的状态</span
            >
          </template>
        </VActionBar>
      </template>
      <template #operation="{ row }">
        <el-button link type="primary" @click="handleEdit(row)">
          编辑
        </el-button>
        <el-button link type="primary" @click="handleSyncRow(row)">
          同步燃油费
        </el-button>
        <el-button link type="primary" @click="handleLog(row)">
          日志
        </el-button>
      </template>
    </VTable>
    <Add
      :id="addId"
      v-model="addVisible"
      :option="optionsDataAll"
      @close="addId = null"
      @refresh="refresh"
    />
    <Log
      dialog
      v-model="logVisible"
      :autoLoad="false"
      tag="sys.fuel-rate"
      :business_id="logId"
      @close="logId = ''"
    />
    <ImportDialog ref="importDialogRef" @refresh="refresh" />
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  </VPage>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import Log from "@/components/Log/index.vue";
import XForm from "@/components/XForm/index.vue";
import Add from "./add/index.vue";
import { useEnumSelect } from "@/hooks/useEnumSelect.js";
import { syncFuelRate, deleteFuelRate, getFuelRateList } from "./api";
import { tipMessage, getTableSelect, getTableSelectRow } from "@/hooks/tool.js";
import { getChannelList } from "@/api/index.js";
import { logisticsSettingsAuthList } from "@/Auth/logistics-settings.js";
import ImportDialog from "@/components/importDialogParams/index.vue";
import DerivedCenter from "@/components/DerivedCenter";
import { config_name } from "@/config/export.js";
import { renderCustomSlot } from "@/hooks/renderTable.jsx";
const { proxy } = getCurrentInstance();
const tableRef = ref();
const tableOptins = reactive({
  formConfig: {
    data: {
      main_channel_id: "",
      relate_channel_ids: "",
      time: { type: "create_time", value: [], range: false }, // 组合+日期范围
      user: { type: "create_user", value: [], range: false }, // 组合+日期范围
    },
  },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    { fixed: "left", width: 50, type: "checkbox" },
    { fixed: "left", width: 50, title: "编号", field: "id" },
    {
      fixed: "left",
      title: "主物流渠道",
      minWidth: 200,
      field: "main_channel_name",
    },
    {
      title: "关联物流渠道",
      minWidth: 200,
      field: "relate_channel_names",
      slots: renderCustomSlot("relate_channel_names"),
    },
    {
      title: "燃油费率(%)",
      width: 100,
      field: "fuel_rate",
    },
    { title: "生效时间", width: 170, field: "start_time" },
    { title: "结束时间", width: 170, field: "end_time" },
    { title: "同步时间", width: 170, field: "sync_time" },
    {
      title: "状态",
      width: 100,
      field: "time_val_status",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <el-tag
                type={
                  row.time_val_status == "待生效"
                    ? "warning"
                    : row.time_val_status == "生效中"
                    ? "primary"
                    : "danger"
                }
              >
                {row.time_val_status}
              </el-tag>
            </div>
          );
        },
      },
    },
    { title: "备注", minWidth: 200, field: "remark" },
    { title: "创建人", width: 170, field: "create_user" },
    { title: "创建时间", width: 170, field: "create_time" },
    { title: "更新人", width: 170, field: "update_user" },
    { title: "更新时间", width: 170, field: "update_time" },

    {
      title: "操作",
      width: 200,
      fixed: "right",
      slots: { default: "operation" },
    },
  ],
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page, form }) => {
        return getFuelRateList({ ...form, ...page }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});
const publicStyle = { style: { width: "240px" } };
const fieldList = [
  {
    field: "main_channel_id",
    type: "select",
    originOption: "channel",
    ...publicStyle,
    options: {
      placeholder: "物流渠道",
      labelKey: "channel_name",
      valueKey: "channel_id",
    },
  },
  {
    field: "relate_channel_ids",
    type: "select",
    originOption: "channel",
    multiple: true,
    ...publicStyle,
    options: {
      placeholder: "关联物流渠道",
      labelKey: "channel_name",
      valueKey: "channel_id",
    },
    class: "select-wrapper-style",
  },
  {
    field: "time",
    type: "dateTimeRange",
    style: { width: "360px" },
    selectStyle: { width: "100px" },
    select: [
      { label: "生效时间", value: "start_time" },
      { label: "结束时间", value: "end_time" },
    ],
    itemProps: {
      startPlaceholder: "最早时间",
      endPlaceholder: "最晚时间",
    },
  },
  {
    field: "user",
    selectStyle: { width: "100px" },
    select: [
      { label: "创建人", value: "create_user" },
      { label: "更新人", value: "update_user" },
    ],
    options: {
      placeholder: "请选择",
    },
    slot: "create_user",
  },
];
const channelData = ref([]);
const getChannel = async () => {
  const { data } = await getChannelList();
  channelData.value = data;
};
getChannel();
const optionsDataAll = computed(() => {
  return {
    channel: channelData.value,
  };
});
const addId = ref(null);
const addVisible = ref(false);
const handleEdit = (val) => {
  addId.value = val.id;
  addVisible.value = true;
};

const handleSync = () => {
  const id = getTableSelect(tableRef.value);
  if (!id.length) return ElMessage.warning("请至少选择一条数据!");
  handleSyncReq(id);
};

const handleSyncRow = (row) => {
  handleSyncReq([row.id]);
};
const handleDelete = () => {
  const id = getTableSelect(tableRef.value);
  if (!id.length) return ElMessage.warning("请至少选择一条数据!");
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认删除选中的
        <span class="text-[#3366F1] px-[4px]">{id.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message, data } = await deleteFuelRate({ id });
          if (code != 200) {
            ElMessage.error(message);
            return;
          }
          tipMessage(data);
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};
const handleSyncReq = (id) => {
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        选中的
        <span class="text-[#3366F1] px-[4px]">{id.length || 1}</span>
        条数据,是否将当前燃油费同步给“主物流渠道”和“关连物流渠道”？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message, data } = await syncFuelRate({
            id,
          });
          if (code != 200) {
            ElMessage.error(message);
            return;
          }
          tipMessage(data);
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};

const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};

const logId = ref("");
const logVisible = ref(false);
const handleLog = (item) => {
  logId.value = item.id;
  logVisible.value = true;
};

//导出中心
const DerivedCenterRef = ref();
const handleExport = () => {
  let condition = getTableSelectRow(tableRef.value);
  DerivedCenterRef.value?.open({
    tag_name: config_name["logistics_settings"]["export_conf_fuel_rate"],
    condition,
  });
};
//导入
const importDialogRef = ref();
const handleImport = () => {
  importDialogRef.value?.open({
    type: "confFuelRate",
    urlType: "/v2/business-import/conf-fuel-rate",
  });
};
const actions = [
  {
    label: "新增",
    icon: "add2",
    type: "primary",
    fn: () => (addVisible.value = true),
    permission: [logisticsSettingsAuthList.fuel_synchronization.add],
  },
  {
    label: "同步燃油费",
    fn: handleSync,
    permission: [
      logisticsSettingsAuthList.fuel_synchronization.synchronization,
    ],
  },
  {
    label: "删除",
    icon: "del",
    fn: handleDelete,
    permission: [logisticsSettingsAuthList.fuel_synchronization.delete],
  },
  {
    label: "导入",
    right: true,
    dkicon: "icon-Download",
    fn: handleImport,
    permission: [logisticsSettingsAuthList.fuel_synchronization.import],
  },
  {
    label: "导出",
    right: true,
    dkicon: "icon-Upload",
    fn: handleExport,
    permission: [logisticsSettingsAuthList.fuel_synchronization.import],
  },
];
</script>
<style lang="scss" scoped>
:deep(.el-tag.el-tag--danger){
    background-color: var(--base-danger-bg)
}
:deep(.el-tag.el-tag--primary){
   background-color: var(--base-primary-bg);
   border-color: var(--base-primary-bg);;
}
</style>
